<template>
  <TreeSelect
    v-model:value="checked"
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="请选择"
    allow-clear
    tree-default-expand-all
    :tree-data="treeData"
    :dropdownMatchSelectWidth="false"
    :field-names="{ children: 'children', label: 'name', value: 'id' }"
    @change="handleChange"
  >
    <template #title="{ name, departmentType }">
      <a-tag color="processing" v-if="departmentType === 1">公司</a-tag>
      <a-tag color="warning" v-else-if="departmentType === 0">部门</a-tag>
      {{ name }}
    </template>
  </TreeSelect>
</template>
<script lang="ts" setup>
  import { TreeSelect } from 'ant-design-vue';
  import { onMounted, ref, watch } from 'vue';
  import { getDepartmentTree } from '/@/api/system/department';

  const treeData = ref<Recordable[]>([]);

  const props = defineProps({
    value: String,
  });

  const checked = ref(undefined);

  const emit = defineEmits(['options-change', 'update:value']);

  // Embedded in the form, just use the hook binding to perform form verification

  onMounted(() => {
    fetch();
  });

  watch(
    () => props.value,
    (val: any) => {
      checked.value = val || undefined;
    },
    {
      immediate: true,
    },
  );

  async function fetch() {
    treeData.value = ((await getDepartmentTree()) as unknown as Recordable[]) || [];
    emit('options-change', treeData.value);
  }

  //多选
  // function handleChange(...args) {
  //   emit('change', ...args);
  // }

  //单选
  function handleChange(value) {
    emit('update:value', value);
  }
</script>
